package com.hz.ruoyimotor.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hz.rouyigonggong.domain.LgDriver;

import com.hz.rouyigonggong.domain.basedomain.BaseDomain;
import com.hz.rouyigonggong.utils.AliOssUtil;
import com.hz.rouyigonggong.utils.ResultJSON;

import com.hz.ruoyimotor.api.service.LgCold;
import com.hz.ruoyimotor.api.service.LgOrder;

import com.hz.ruoyimotor.domain.LgTemperature;
import com.hz.ruoyimotor.mapper.LgDriverMapper;
import com.hz.ruoyimotor.service.LgDriverColdService;
import com.hz.ruoyimotor.service.LgDriverService;
import com.hz.ruoyimotor.service.LgTemperatureService;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author gj
 * @version 1.0
 * @date 2025/3/3 14:02
 */

@RestController
@RequestMapping("/driver")
public class LgDriverController {
    @Autowired
    private LgDriverService lgDriverService;
    @Autowired
    private LgDriverColdService lgDriverColdService;
    @Autowired
    private LgCold lgCold;
    @Autowired
    private LgOrder lgOrder;
    @Autowired
    private LgDriverMapper lgDriverMapper;
    @Autowired
    private LgTemperatureService lgTemperatureService;

    //查询司机信息
        @RequiresPermissions("motor:driver:getAll")
        @GetMapping("/getAll")
        public AjaxResult getAll(@RequestParam Map<String, Object> params,Integer pageNum, Integer pageSize) {
            params.put("createBy",String.valueOf(BaseDomain.getUserId()));
            Integer firstNum = (pageNum-1)*pageSize;
             Integer secondNum = pageSize;


             return  AjaxResult.success(lgDriverService.getReallyList(params,firstNum,secondNum));
        }
        //查询司机总数
    @RequiresPermissions("motor:driver:getTotal")
    @RequestMapping("/getTotal")
    public ResultJSON getTotal(@RequestParam Map<String, Object> params){
        params.put("createBy",String.valueOf(BaseDomain.getUserId()));
        return ResultJSON.success(lgDriverService.getCount(params));

    }
    //删除司机信息
    @RequiresPermissions("motor:driver:delete")
    @DeleteMapping("/{driverIds}")
    public AjaxResult delDriver(@PathVariable String[] driverIds)
    {
        return AjaxResult.success(lgDriverService.deleteBatchIds(driverIds));

    }
    //添加司机信息
    @RequiresPermissions("motor:driver:add")
    @PostMapping("/addDriver")
    public ResultJSON addVehicle(@RequestBody LgDriver lgDriver){
        lgDriver.setCreateBy(String.valueOf(BaseDomain.getUserId()));
        return ResultJSON.success(lgDriverService.save(lgDriver));
    }
    //修改司机信息
    @RequiresPermissions("motor:driver:update")
    @PostMapping("/updateDriver")
    public ResultJSON updateDriver(@RequestBody LgDriver lgDriver){
        System.out.println("------------------"+lgDriverService.updateById(lgDriver));
        return ResultJSON.success(lgDriverService.updateById(lgDriver));
    }
    //查询司机信息
    @RequiresPermissions("motor:driver:getDriverById")
    @GetMapping(value = "/{driverId}")
    public ResultJSON getDriverById(@PathVariable Integer driverId){
        System.out.println("driverId"+driverId);

        return ResultJSON.success(lgDriverService.getById(driverId));
    }
    //查冷酷全部信息
    @RequiresPermissions("motor:driver:cold")
    @GetMapping(value = "/getListCold")
    @GlobalTransactional//分布式事务
    public ResultJSON getListCold(@RequestParam("pageNum")Integer pageNum,
                                  @RequestParam("pageSize")Integer pageSize){
        System.out.println("Received pageNum: " + pageNum + " pageSize: " + pageSize);

        System.out.println(lgCold.getColdSome(pageNum,pageSize));
             return lgCold.getColdSome(pageNum,pageSize);
    }
    @RequiresPermissions("motor:driver:count")
    @GetMapping(value = "/getColdCount")
    @GlobalTransactional//分布式事务
    public ResultJSON getColdCount(){


        return lgCold.getColdCount();
    }

    //查冷库名称
    @PostMapping("/getStorageUserList")
    public ResultJSON getStorageUserList(){
        return
                ResultJSON.success(lgDriverColdService.getStorageUserList());
    }
    @RequiresPermissions("motor:driver:export")
    @Log(title = "司机", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LgDriver lgDriver)
    {

        List<LgDriver> list = lgDriverService.list(null);
        ExcelUtil<LgDriver> util = new ExcelUtil<LgDriver>(LgDriver.class);
        util.exportExcel(response, list, "司机数据");
    }


    //app端司机的登录方法
    @PostMapping("/login")
    public ResultJSON login(@RequestBody Map<String,Object> map){
             String username = (String) map.get("username");
             String password = (String) map.get("password");
             if(username==null||password==null){
                 return ResultJSON.error();
             }
        QueryWrapper<LgDriver> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",username);
        queryWrapper.eq("password",password);
        return ResultJSON.success(lgDriverService.getOne(queryWrapper));
    }

    //根据司机id拿到入库订单
    @GetMapping("/getOrder/{driverId}")
    @GlobalTransactional//分布式事务
    public ResultJSON getOrder(@PathVariable String driverId){
             Integer cc = Integer.parseInt(driverId);
        return lgOrder.getOrderSome(cc);
    }
    //根据司机id拿到出库订单
    @GetMapping("/getOut/{driverId}")
    @GlobalTransactional//分布式事务
    public ResultJSON getOut(@PathVariable String driverId){
        Integer cc = Integer.parseInt(driverId);
        System.out.println("++++++++++++++++++++"+lgOrder.getOutSome(cc));
        return lgOrder.getOutSome(cc);
    }
    //根据id获得单个司机信息
    @GetMapping("/getDriverMessage/{driverId}")
    public ResultJSON getDriverMessage(@PathVariable String driverId){
        Integer cc = Integer.parseInt(driverId);
        return ResultJSON.success(lgDriverMapper.getDriverMessage(cc));
    }
    //修改司机信息
    @PostMapping("/updateDriverMessage")
    public ResultJSON updateDriverMessage(@RequestBody LgDriver lgDriver){
        System.out.println("修改司机状态为1");
        return ResultJSON.success(lgDriverMapper.updateDriverMessage(lgDriver));
    }
    //接收从前端传过来的图片
    @PostMapping("/upload")
    public ResultJSON upload(@RequestParam("file") MultipartFile file) {
        System.out.println("111111111111111111111111111111");
        if (file.isEmpty()) {
            return ResultJSON.error("文件为空");
        }

        try {
            // 1. 将 MultipartFile 转换为二进制数组
            byte[] fileBytes = file.getBytes();

            // 2. 生成唯一的 UUID
            String uuid = UUID.randomUUID().toString()+".png";

            // 3. 调用上传至云端的方法（假设有一个方法名为 uploadToCloud）
            String fileUrl = AliOssUtil.upload(fileBytes, uuid);
            System.out.println("文件上传成功，文件地址为：" + fileUrl);
            if (fileUrl.length()>=0) {
                return ResultJSON.success(fileUrl);
            } else {
                return ResultJSON.error(fileUrl);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJSON.error("文件处理失败: " + e.getMessage());
        }
    }


    //查询当前温湿度，gps信息
    @GetMapping("/getColdMessage/{driverId}")
    public ResultJSON getColdMessage(@PathVariable Integer driverId){
        System.out.println("车辆id------------------"+driverId);
        QueryWrapper<LgTemperature> queryWrapper = new QueryWrapper();
        queryWrapper.eq("bound_id",driverId);
        //将数据存储进redis
//        RedisUtil.set("temperature"+driverId,lgTemperatureService.getOne(queryWrapper));
        return ResultJSON.success(lgTemperatureService.getOne(queryWrapper));
    }

    //修改司机状态
    @PostMapping("/updateDriverStatus")
    public ResultJSON updateDriverStatus(@RequestBody LgDriver lgDriver){
        System.out.println("修改司机状态为1");
        return ResultJSON.success(lgDriverMapper.updateDriverStatus(lgDriver));
    }
//    //获得司机端传过来的质检信息
//    @PostMapping("/getColdMessage")
//    public ResultJSON getColdMessage(@RequestBody Map<String,Object> map){
////        System.out.println("-------------------"+map);
//
//        return ResultJSON.success();
//    }
//    //修改订单状态
//    @PostMapping("/updateDriverStatus")
//    public ResultJSON updateDriverStatus(@RequestBody Map<String,Object> map){
//        System.out.println("-------------------"+map);
//        return ResultJSON.success();
//    }
   //买家根据手机号查询
    @GetMapping("/getBuyer/{buyerPhone}")
    @GlobalTransactional//分布式事务
    public ResultJSON getBuyer(@PathVariable String buyerPhone){
        return lgOrder.getBuyerSome(buyerPhone);
    }
}
